<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="560" :visible="visible" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form ref="formRef" :model="formState" :rules="modalRules" class="p-20 pb-2" layout="vertical" :label-col="{ span: 23 }" :wrapper-col="{ span: 23 }"> 
        <a-form-item :label="$t('video.monitorCode')" name="code" >
          <a-input v-model:value.trim="formState.code" :placeholder="$t('common.pleaseInput')" :maxLength="29" />
        </a-form-item> 
        <a-form-item :label="$t('video.monitorName')" name="name">
          <a-input v-model:value.trim="formState.name" :placeholder="$t('video.pleaseInputMonitorName')" :maxLength="29" />
        </a-form-item>
        <a-form-item :label="$t('video.brandName')" name="brand">
          <a-select  v-model:value="formState.brand" :placeholder="$t('common.pleaseSelect')">
            <a-select-option v-for="(item, index) in [{ value: 1, text: $t('video.hik')}]" :key="index" :value="item.value">{{item.text}}</a-select-option>
          </a-select>
        </a-form-item> 
        <a-form-item :label="$t('video.belongWaterLine')" name="hangerLineId">
          <a-select  v-model:value="formState.hangerLineId" :placeholder="$t('common.pleaseSelect')" @change="getStationList(true)">
            <a-select-option v-for="(item, index) in lineList" :key="index" :value="item.id">{{item.lineNo}}</a-select-option>
          </a-select>
        </a-form-item> 
        <a-form-item :label="$t('video.belongStation')" name="stationId">
          <a-select  v-model:value="formState.stationId" :placeholder="$t('common.pleaseSelect')" :disabled="!formState.hangerLineId" >
            <a-select-option v-for="(item, index) in stationList" :key="index" :value="item.id">{{item.stationNo}}</a-select-option>
          </a-select>
        </a-form-item>  
        <a-form-item :label="$t('video.deviceSerialNo')" name="deviceSerial">
          <a-input v-model:value.trim="formState.deviceSerial" :placeholder="$t('video.pleaseInputDeviceSerialNo')" :maxLength="99" @change="getIpcList">
          </a-input>
        </a-form-item>  
        <a-form-item :label="$t('video.ipcSerialNo')" name="channelNo">
          <a-select  v-model:value="formState.channelNo" :placeholder="$t('common.pleaseSelect')" :disabled="!formState.deviceSerial" >
            <a-select-option v-for="(item, index) in ipcList" :key="index" :value="item.channelNo">{{item.ipcSerial}}</a-select-option>
          </a-select>
        </a-form-item>  
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="operateEmpModal">
import { ref, nextTick, onMounted, computed } from 'vue'
import {cloneDeep, pick} from 'lodash'
import axios from '@/utils/request'
import {getFieldText} from '@/utils'
import { message } from 'ant-design-vue' 
import { modalRules } from './config'
import { store } from '@/store'
import i18n from '@/locales/index'

const { t } = i18n.global
const lineList = computed(() => {
  return store.state.normalData.waterList
})
let ipcList = ref([])
const stationList = ref([])
const emits = defineEmits(['ok'])
let visible = ref(false)
let confirmLoading = ref(false)
let formState = ref({})
let operateType = ref('')
let title = ref('')
const formRef = ref()
 
let recordInfo = ref({})
const edit = async (record,typeValue) => {
  // console.log(record)
  visible.value = true
  recordInfo.value = {}
  title.value = t('video.addSDevice')
  operateType.value = 'add'
  if (typeValue){
    let records = cloneDeep(record)
    title.value = t('video.editDevice')
    operateType.value = 'edit'
    recordInfo.value = pick(records,["id","code", "name", "brand", "hangerLineId", "stationId", "deviceSerial", "channelNo"])
  }
  await nextTick()
  formState.value = recordInfo.value
  formRef.value.resetFields()
  await getIpcList()
  await getStationList(false)
}
const handleOk = async () => {
  try {
    await formRef.value.validateFields()
    let params = cloneDeep(formState.value)
    // 增加icp参数
    params.ipcSerial =  getFieldText(ipcList.value, params.channelNo, 'channelNo', 'ipcSerial')
    confirmLoading.value = true
    let url = operateType.value == 'edit' ? '/api/monitor/device/update' : '/api/monitor/device/create'
    // let url = '/api/monitor/device/create'
    let res = await axios.postAction(url, params)
    confirmLoading.value = false
    if (res.success) {
      message.success(res.msg)
      emits('ok')
      createVideo(res.data)
      handleCancel()
    } else {
      message.warning(res.msg)
      confirmLoading.value = false
    }
  } catch {
    confirmLoading.value = false
    console.log('error')
  }
}
const handleCancel = () => {
  formState.value = {}
  confirmLoading.value = false
  formRef.value.resetFields()
  visible.value = false
}
const createVideo = async (monitorCode) => { 
  let {deviceSerial, hangerLineId, stationId,channelNo} = formState.value
  let params = { 
    monitorCode,
    channelNo,
    deviceSerial,
    hangerLineId,
    hangerLineNo: getFieldText(lineList.value, hangerLineId, 'id', 'lineNo'), 
    stationNo: getFieldText(stationList.value, stationId, 'id', 'stationNo')
   }
  await axios.postAction('/api/monitor/video/create', params) 
}
const getStationList = async (stationIdReset) => {
  // formState.value.stationId = []
  if (stationIdReset){
    formState.value.stationId = ''
  }
  if(!formState.value.hangerLineId) return
  try {
    const res = await axios.postAction('/api/device/station/page', {
      pageNo: 1,
      pageSize: 999999,
      hangerLineId: formState.value.hangerLineId
    })
    stationList.value = res.success? (res?.data?.list ||[]) : []
  } catch {
    stationList.value = []
  }
} 
// 获取通道列表
const getIpcList = async()=> {
  if(!formState.value.deviceSerial) return
  try {
    const res = await axios.postAction('/api/monitor/device/listChannel', {
      pageNo: 1,
      pageSize: 999999,
      deviceSerial: formState.value.deviceSerial
    })
    ipcList.value = res.success? (res?.data ||[]) : []
  } catch {
    ipcList.value = []
  }
}
onMounted(async () => {
  store.dispatch('getWater')
})
defineExpose({
  edit
})

</script>